/*
*Copyright (c) Nikhil Jain.
*Project ICARUS, communications and 
*artificial intelligence.
*/



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
 */
package javadrone.client;

//~--- non-JDK imports --------------------------------------------------------

import javadrone.Drone;

import javadrone.command.*;
import javadrone.command.CommandExecutor;
import javadrone.command.ExecutorException;

//~--- JDK imports ------------------------------------------------------------

import java.rmi.RemoteException;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Nikzzay
 */
public class CommandConsumer {
    private Thread commandFollower = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                takeCommand();
            } catch (RemoteException | InterruptedException | ExecutorException ex) {
                Logger.getLogger(CommandConsumer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    private CommandExecutor ce;
    private Drone           commandDrone;
    private boolean         startFlag;

    public CommandConsumer(Drone D, CommandExecutor ce) {
        commandDrone = D;
        this.ce      = ce;
    }

    public void start() {
        startFlag = true;
        commandFollower.start();
    }

    public void stop() {
        startFlag = false;
    }

    public void takeCommand() throws RemoteException, InterruptedException, ExecutorException {
        while (startFlag) {
            System.out.println("Waiting for next command..." + commandDrone.commandsInQueue());

            Command nextCommand = commandDrone.takeCommand();

            nextCommand.execute(ce);

            if (nextCommand.getDescriptor().equals(CommandDescriptor.QUIT)) {
                System.out.println("Command executed: " + nextCommand);

                break;
            }

            System.out.println("Command executed: " + nextCommand);
        }

        System.out.println("Killed...");
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
